package logic

import (
	"github.com/gogap/logs"
	"log"
	"strings"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/pkg/wechatpay"
)

/**
* 微信JSAPI支付 ---- V3
 */
func (logic *OrderLogic) HandleWxTransactionsPayV3(param *request.CreateOrderReq, wc *paysetting.PaySetting) (respData *wechatpay.PayData, tradeNo string, err error) {

	apiData := logic.TransactionsPayApiParamV3(param, wc)
	logs.Info("统一下订单,生成的apiData =============> body", apiData.ToJson())
	tradeNo = apiData.Get("out_trade_no")
	respData, err = wechatpay.ApiJsApiPay(apiData, wc) // 请求微信API
	//log.Println("统一下订单返回结果 ", respData)
	return
}

func (logic *OrderLogic) HandleMakeSignV3(respData *wechatpay.PayData, wc *paysetting.PaySetting, tradeNo string) *wechatpay.PayData {
	nonceStr := strings.ToUpper(wechatpay.RandomStr(32))
	timeStamp := wechatpay.TimeStamp()
	packageStr := "prepay_id=" + respData.Get("prepay_id")

	resultData := wechatpay.NewPayData()
	resultData.Set("appId", wc.AppId)
	resultData.Set("timeStamp", timeStamp)
	resultData.Set("nonceStr", nonceStr)
	resultData.Set("package", packageStr)
	resultData.Set("signType", "RSA")

	paySign, _ := wechatpay.GenerateSignPay(wc.AppId, timeStamp, nonceStr, packageStr, wc)
	resultData.Set("paySign", paySign)
	resultData.Set("tradeNo", tradeNo)

	return resultData
}

/**
* 微信订单金额退款 ---- V3
* @refundMoney 退款金额
* @orderInfo 订单信息
 */
func (logic *OrderLogic) HandleWxCancelOrderByMoney(refundMoney int64, orderInfo *orders.OrderModel) (respData *wechatpay.PayData, err error) {
	var wc *paysetting.PaySetting
	if orderInfo.Appid != "" {
		wc = NewSettingLogic().GetPaySettingByAppidAndMchid(orderInfo.Appid, orderInfo.Mchid)
	} else {
		wc = logic.WxConfig
	}

	reason := "押金退款"
	apiParam := logic.HandleRefundApiParamV3(
		orderInfo,
		orderInfo.OutTradeNo,
		reason,
		refundMoney,
		wc.RefundNotifyUrl)

	rData, err := wechatpay.ApiRefundsPayScore(apiParam, wc)

	log.Println("打印测试数据---退款返回后的数据", rData)

	return rData, err
}

func (logic *OrderLogic) HandleWxCancelOrderCash(refundMoney int64, orderInfo *orders.OrderModel) (respData *wechatpay.PayData, err error) {
	wc := NewSettingLogic().GetPaySettingByAppidAndMchid(orderInfo.Appid, orderInfo.Mchid)
	reason := "押金退款"
	apiParam := logic.HandleRefundApiParamV3(
		orderInfo,
		orderInfo.OutTradeNo,
		reason,
		refundMoney,
		wc.RefundNotifyUrlCash)

	rData, err := wechatpay.ApiRefundsPayScore(apiParam, wc)

	log.Println("打印测试数据---退款返回后的数据", rData)

	return rData, err
}
